import os
import time

from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import Shop
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime


# 店铺信息管理的视图文件
# Create your views here.

def index(request, pIndex=1):  # 浏览信息
    smod = Shop.objects
    slist = smod.filter(status__lt=9)
    # 获取并判断搜索条件
    mywhere = []
    kw = request.GET.get("keyword", None)
    if kw:
        slist = slist.filter(Q(name__contains=kw) | Q(address__contains=kw))
        mywhere.append('keyword=' + kw)
    slist = slist.order_by("id")    # 对id排序
    # 执行分页处理
    pIndex = int(pIndex)
    page = Paginator(slist, 4)  # 以每页5条数据分页
    maxpage = page.num_pages  # 获取最大页数
    # 判断当前页是否越界
    if pIndex > maxpage:
        pIndex = maxpage
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 获取当前页
    plist = page.page_range  # 获取页码列表
    context = {"shoplist": list2, "plist": plist, "pIndex": pIndex, "maxpage": maxpage, "mywhere": mywhere}
    return render(request, "myadmin/shop/index.html", context)


def add(request):  # 添加信息表单
    return render(request, "myadmin/shop/add.html")


def insert(request):  # 执行信息添加
    try:
        # 实例化model，封装信息，并执行添加操作
        ob = Shop()
        ob.name = request.POST['name']
        ob.address = request.POST['address']
        ob.phone = request.POST['phone']

        # 店铺封面图片的上传处理
        myfile = request.FILES.get("cover_pic", None)
        if not myfile:
            print(myfile)
            return HttpResponse("没有店铺封面上传文件信息！")
        cover_pic = str(time.time()).split('.').pop()+'.'+myfile.name.split('.').pop()
        destination = open("./static/uploads/shop/"+cover_pic, "wb+")
        for chunk in myfile.chunks():
            destination.write(chunk)
        destination.close()

        # 店铺logo图片的上传处理
        myfile = request.FILES.get("banner_pic", None)
        if not myfile:
            print(myfile)
            return HttpResponse("没有店铺logo上传文件信息！")
        banner_pic = str(time.time()) + '.' + myfile.name.split('.').pop()
        destination = open("./static/uploads/shop/" + banner_pic, "wb+")
        for chunk in myfile.chunks():
            destination.write(chunk)
        destination.close()

        ob.cover_pic = cover_pic
        ob.banner_pic = banner_pic
        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '添加成功'}
    except Exception as err:
        print(err)
        context = {'info': '添加失败'}
    return render(request, "myadmin/info.html", context)


def delete(request, uid=0):  # 执行删除信息
    try:
        ob = Shop.objects.get(id=uid)
        ob.status = 9
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '删除成功'}
    except Exception as err:
        print(err)
        context = {'info': '删除失败'}
    return render(request, "myadmin/info.html", context)


def edit(request, uid=0):  # 加载信息编辑表单
    try:
        ob = Shop.objects.get(id=uid)
        context = {'shop': ob}
        return render(request, "myadmin/shop/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': '没有找到修改的信息'}
        return render(request, "myadmin/info.html", context)


def update(request, uid=0):  # 执行信息编辑
    try:
        ob = Shop.objects.get(id=uid)

        old_cover_pic = ob.cover_pic
        my_cover_pic = request.FILES.get("cover_pic", None)
        if not my_cover_pic:
            cover_pic = old_cover_pic
        else:
            cover_pic = str(time.time())+'.'+my_cover_pic.name.split('.').pop()
            destination = open("./static/uploads/shop/"+cover_pic, "wb+")
            for chunk in my_cover_pic.chunks():
                destination.write(chunk)
            destination.close()

        old_banner_pic = ob.banner_pic
        my_banner_pic = request.FILES.get("banner_pic", None)
        if not my_banner_pic:
            banner_pic = old_banner_pic
        else:
            banner_pic = str(time.time()) + '.' + my_banner_pic.name.split('.').pop()
            destination = open("./static/uploads/shop/" + banner_pic, "wb+")
            for chunk in my_banner_pic.chunks():
                destination.write(chunk)
            destination.close()

        ob.name = request.POST['name']
        ob.address = request.POST['address']
        ob.phone = request.POST['phone']
        ob.cover_pic = cover_pic
        ob.banner_pic = banner_pic
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '修改成功！'}

        if my_cover_pic:
            os.remove("./static/uploads/shop/"+old_cover_pic)

        if my_banner_pic:
            os.remove("./static/uploads/shop/" + old_banner_pic)
    except Exception as err:
        print(err)
        context = {'info': '修改失败！'}
        if my_cover_pic:
            os.remove("./static/uploads/product/" + cover_pic)

        if my_banner_pic:
            os.remove("./static/uploads/shop/" + banner_pic)
    return render(request, "myadmin/info.html", context)
